package Lab15;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class DataFile {
    //每次对文件操作，全部清空旧数据，把新数据写回文件中
    public static void InCusFile() throws Exception {
        File inputFile = new File("Cus.txt");// 创建File对象
        if (!inputFile.exists()) {
            return; // 如果文件不存在，直接返回
        }
        //创建输入流
        //创建BufferedReader对象，从文件读取数据，读完后写回单例
        try(BufferedReader in = new BufferedReader(new FileReader(inputFile))){
            String line;
            //获取客户单例
            List<CustomerInfo> customerInfos = CustomerSigleList.getCustomerInfos();
            customerInfos.clear(); // 清空现有数据
            
            while ((line = in.readLine()) != null) {
                //从文件读取数据，解析并写回单例
                CustomerInfo customerInfo = parseCustomerInfo(line);
                if (customerInfo != null) {
                    customerInfos.add(customerInfo);
                }
            }
        }
    }
    public static void OutCusFile() throws Exception {
        File outputFile = new File("Cus.txt");
        // 如果输出文件不存在，则创建它
        if (!outputFile.exists()) {
            outputFile.createNewFile();
        }
        //获取客户单例
        List<CustomerInfo> customerInfos = CustomerSigleList.getCustomerInfos();
        try (
            BufferedWriter out = new BufferedWriter(new FileWriter(outputFile))){
            for (CustomerInfo customerInfo : customerInfos) {
                out.write(customerInfo.toString());
                out.newLine();
            }
        }

    }
    public static void InPlaneFile() throws Exception {
        File inputFile = new File("Plane.txt");// 创建File对象
        if (!inputFile.exists()) {
            return; // 如果文件不存在，直接返回
        }
        try(BufferedReader in = new BufferedReader(new FileReader(inputFile))){
            String line;
            //获取航班单例
            List<PlaneInfo> planeInfos = PlaneInfoSigleList.getPlaneInfos();
            planeInfos.clear(); // 清空现有数据
            
            while ((line = in.readLine()) != null) {
                //从文件读取数据，解析并写回单例
                PlaneInfo planeInfo = parsePlaneInfo(line);
                if (planeInfo != null) {
                    planeInfos.add(planeInfo);
                }
            }
        }
    }
    public static void OutPlaneFile() throws Exception {
        File outputFile = new File("Plane.txt");
        if (!outputFile.exists()) {
            outputFile.createNewFile();
        }
        List<PlaneInfo> planeInfos = PlaneInfoSigleList.getPlaneInfos();
        try (
            BufferedWriter out = new BufferedWriter(new FileWriter(outputFile))){
            for (PlaneInfo planeInfo : planeInfos) {
                out.write(planeInfo.toString());
                out.newLine();
            }
        }
    }
    
    // 解析客户信息字符串，创建CustomerInfo对象
    private static CustomerInfo parseCustomerInfo(String line) {
        try {
            // CustomerInfo的toString格式: name,Id,phone,[planeInfos]
            // 需要解析这种格式的字符串
            if (line == null || line.trim().isEmpty()) {
                return null;
            }
            
            // 找到航班信息列表的开始位置（'['字符）
            int bracketIndex = line.indexOf('[');
            if (bracketIndex == -1) {
                return null;
            }
            
            String basicInfo = line.substring(0, bracketIndex - 1); // -1是为了去掉逗号
            String planeInfosStr = line.substring(bracketIndex);
            
            // 解析基本信息: name,Id,phone
            String[] parts = basicInfo.split(",");
            if (parts.length != 3) {
                return null;
            }
            
            CustomerInfo customerInfo = new CustomerInfo();
            customerInfo.setName(parts[0].trim());
            customerInfo.setId(parts[1].trim());
            customerInfo.setPhone(parts[2].trim());
            
            // 解析航班信息列表 (格式: [planeInfo1, planeInfo2, ...])
            List<PlaneInfo> planeInfos = new ArrayList<>();
            if (planeInfosStr.startsWith("[") && planeInfosStr.endsWith("]")) {
                String planeListContent = planeInfosStr.substring(1, planeInfosStr.length() - 1);
                if (!planeListContent.trim().isEmpty()) {
                    // 分割航班信息，每个航班信息以", "分隔
                    // 但需要注意航班信息内部也包含制表符，所以需要特殊处理
                    String[] planeInfoStrings = splitPlaneInfos(planeListContent);
                    for (String planeInfoStr : planeInfoStrings) {
                        PlaneInfo planeInfo = parsePlaneInfo(planeInfoStr.trim());
                        if (planeInfo != null) {
                            planeInfos.add(planeInfo);
                        }
                    }
                }
            }
            customerInfo.setPlaneInfos(planeInfos);
            
            return customerInfo;
        } catch (Exception e) {
            System.err.println("解析客户信息出错: " + line);
            return null;
        }
    }
    
    // 解析航班信息字符串，创建PlaneInfo对象
    private static PlaneInfo parsePlaneInfo(String line) {
        try {
            // PlaneInfo的toString格式: planeId\trouteStart->routeEnd\ttime\tseatNum
            if (line == null || line.trim().isEmpty()) {
                return null;
            }
            
            String[] parts = line.split("\t");
            if (parts.length != 4) {
                return null;
            }
            
            PlaneInfo planeInfo = new PlaneInfo();
            planeInfo.setPlaneId(parts[0].trim());
            
            // 解析航线 (格式: routeStart->routeEnd)
            String route = parts[1].trim();
            String[] routeParts = route.split("->");
            if (routeParts.length == 2) {
                planeInfo.setRouteStart(routeParts[0].trim());
                planeInfo.setRouteEnd(routeParts[1].trim());
            }
            
            planeInfo.setTime(parts[2].trim());
            planeInfo.setSeatNum(Integer.parseInt(parts[3].trim()));
            
            return planeInfo;
        } catch (Exception e) {
            System.err.println("解析航班信息出错: " + line);
            return null;
        }
    }
    
    // 分割航班信息字符串，处理内部包含制表符的情况
    private static String[] splitPlaneInfos(String planeListContent) {
        // 航班信息格式: planeId\trouteStart->routeEnd\ttime\tseatNum
        // 多个航班信息之间用", "分隔
        // 由于航班信息内部包含制表符
        
        List<String> planeInfos = new ArrayList<>();
        if (planeListContent.trim().isEmpty()) {
            return new String[0];
        }
        
        // 简单的分割方法：按", "分割，要确保不会分割航班信息内部的内容
        String[] parts = planeListContent.split(", ");
        for (String part : parts) {
            if (!part.trim().isEmpty()) {
                planeInfos.add(part.trim());
            }
        }
        
        return planeInfos.toArray(new String[0]);
    }
}

